package com.example.auto;

import java.io.File;

import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;

import com.example.auto.ScriptRunner.CMDS;
import com.example.utils.FileUtils;
import com.example.utils.Logger;

/**
 * 只在Xposed空间有效
 */
public class ScriptMaker {
	private static final Logger log = Logger.create("ScriptMaker");
	private static boolean isRecording = false;
	private static StringBuilder sb;
	private static long startTime;

	static{
		log.e("load");
	}
	/**
	 * 开始录制
	 */
	public static void startRecord() {
		if (isRecording)
			return;
		startTime = System.currentTimeMillis();
		sb = new StringBuilder(4096);
		log.e("开始录制脚本");
		isRecording = true;
	}

	/**
	 * 停止录制
	 * 
	 * @param path
	 *            保存路径
	 */
	public static void stopRecording(String path) {
		isRecording = false;
		FileUtils.writeStringToFile(new File(path), sb.toString());
		log.e("停止录制脚本");
	}

	private static boolean isDown;
	private static boolean moved;
	private static float downX;
	private static float downY;
	private static long downTime;

	/**
	 * 驱动 android.view.InputEventReceiver <br/>
	 * private void dispatchInputEvent(int seq, InputEvent event) <br/>
	 */
	public static void onInputEvent(InputEvent e) {
		if (!isRecording)
			return;

		int t = (int) (System.currentTimeMillis() - startTime);

		if (e instanceof MotionEvent) {
			MotionEvent event = (MotionEvent) e;
			float rx = event.getRawX();
			float ry = event.getRawY();

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				// if (isDown) {
				// if(event.getFlags()
				// }

				isDown = true;
				downTime = System.currentTimeMillis();

				downX = rx;
				downY = ry;
			} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
				moved = true;
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				if (isDown) {
					isDown = false;

					if (moved
							&& (Math.abs(rx - downX) <= 5 && Math.abs(ry
									- downY) <= 5)) { // 触屏太灵敏
						moved = false;
					}

					if (moved) {
						sb.append(t).append(" swap ").append(downX).append(' ')
								.append(downY).append(' ').append(rx)
								.append(' ').append(ry).append(' ')
								.append(System.currentTimeMillis() - downTime)
								.append('\n');

						log.i("add swap " + t);
					} else {
						sb.append(t).append(" tap ").append(downX).append(' ')
								.append(downY).append('\n');

						log.i("add tap " + t);
					}
				}
			}
		} else if (e instanceof KeyEvent) {
			KeyEvent event = (KeyEvent) e;

			if (event.getAction() == KeyEvent.ACTION_UP) {
				sb.append(t).append(" key ").append(event.getKeyCode())
						.append('\n');

				log.i("add key " + t);
			}
		}
	}

	public static void addCMD(CMDS cmd) {
		if (!isRecording)
			return;

		int t = (int) (System.currentTimeMillis() - startTime);
		sb.append(t).append(' ').append(cmd.getName()).append('\n');
		log.i("add cmd: " + cmd.getName());
	}

}
